package middleware

import (
	"api/internal/respons"
	"github.com/go-errors/errors"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"smart-health-platforms/pkg"
	"strings"
)


type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 检查是否是WebSocket请求
		isWebSocket := strings.ToLower(r.Header.Get("Upgrade")) == "websocket"

		// 先从Header中获取token
		token := r.Header.Get("token")
		// 如果Header中没有token，尝试从URL参数中获取
		if token == "" {
			token = r.URL.Query().Get("token")
		}

		if token == "" {
			if isWebSocket {
				// 对于WebSocket请求，使用http.Error而不是httpx.OkJsonCtx
				http.Error(w, "token未登录", http.StatusUnauthorized)
			} else {
				resp := respons.Error(400, "token未登录", errors.Error{})
				httpx.OkJsonCtx(r.Context(), w, resp)
			}
			return
		}
		//token不为空时，解析
		getToken, s := pkg.GetToken(token)
		if s != "" {
			if isWebSocket {
				// 对于WebSocket请求，使用http.Error而不是httpx.OkJsonCtx
				http.Error(w, s, http.StatusUnauthorized)
			} else {
				resp := respons.Error(400, s, errors.Error{})
				httpx.OkJsonCtx(r.Context(), w, resp)
			}
			return
		}
		//实例化表单
		r.ParseForm()
		r.Form.Set("userId", getToken["userId"].(string))
		next(w, r)
	}
}
